﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;
using System.Diagnostics;
using System.Management;

namespace FBKPI.ReportHandler
{
    /// <summary>
    /// Summary description for KPIHandoverReportHandler
    /// </summary>
    public class KPIHandoverReportHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string msg = this.Save();
            context.Response.Write(msg);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Save()
        {
            string msg = string.Empty;
            try
            {
                int year = HttpContext.Current.Request.QueryString["Year"].Replace("undefined",string.Empty) == string.Empty ? DateTime.Now.Year : Convert.ToInt32(HttpContext.Current.Request.QueryString["Year"]);
                int KPIAssignDetailID = Convert.ToInt32(HttpContext.Current.Request.QueryString["KPI"]);
                KPIAssignDetail KPIs = new KPIAssignDetailFacade().GetKPIAssignDetailByID(KPIAssignDetailID);
                Employee CurrUser = new EmployeeFacade().GetEmployeeByID(Convert.ToInt32(HttpContext.Current.Request.QueryString["User"]));
                string path = System.Configuration.ConfigurationManager.AppSettings["KPIHandoverReportPath"].ToString();
                string outputFilename = CurrUser.ID.ToString() + "_" + year.ToString() + "_" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".doc";
                string outputPath = System.Configuration.ConfigurationManager.AppSettings["ExportKPIHandoverPath"].ToString() + outputFilename;

                if (KPIs != null)
                {
                    ReportFacade Rf = new ReportFacade();
                    msg = Rf.GenerateHandoverKPI(year, CurrUser, path, outputPath, KPIs);
                }
                else
                    msg = "Invalid KPI";
            }
            catch (Exception ex)
            {
                Tools.LogWriter.LogWriter logwriter = new Tools.LogWriter.LogWriter();
                logwriter.WriteLog(ex.Message, ex.StackTrace.ToString());
                msg = "Error while generate KPI Handover file, please contact IT suppport";
            }
            

            var gridData = new
            {
                msg
            };
            var JSONSerializer = new JavaScriptSerializer();
            return JSONSerializer.Serialize(gridData);
        }
    }
}